import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  message, 
  Modal, 
  Form, 
  Input, 
  Space, 
  Tag,
  DatePicker,
  Select,
  Descriptions,
  Card,
  Divider
} from 'antd';
import { 
  EyeOutlined, 
  SearchOutlined, 
  ReloadOutlined 
} from '@ant-design/icons';
import { orderApi } from '../../api';

const { RangePicker } = DatePicker;
const { Option } = Select;

const Orders = () => {
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  
  // 订单详情相关状态
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState(null);
  const [detailLoading, setDetailLoading] = useState(false);

  // 搜索条件
  const [searchParams, setSearchParams] = useState({
    bookName: '',
    startTime: null,
    endTime: null
  });

  // 订单状态映射
  const ORDER_STATUS = {
    0: { text: '待付款', color: 'orange' },
    1: { text: '已付款', color: 'blue' },
    2: { text: '已发货', color: 'green' },
    3: { text: '已完成', color: 'success' },
    4: { text: '已取消', color: 'red' }
  };

  // 获取订单列表
  const fetchOrders = async (page = 0, size = 10, params = {}) => {
    setLoading(true);
    try {
      const queryParams = {
        page,
        size,
        ...params
      };
      
      const response = await orderApi.getAllOrders(queryParams);
      if (response.success) {
        setOrders(response.data.content || []);
        setPagination({
          current: page + 1,
          pageSize: size,
          total: response.data.totalElements || 0
        });
      } else {
        message.error(response.message || '获取订单列表失败');
      }
    } catch (error) {
      console.error('获取订单列表错误:', error);
      message.error('获取订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取订单详情
  const fetchOrderDetail = async (orderId) => {
    setDetailLoading(true);
    try {
      const response = await orderApi.getOrderById(orderId);
      if (response.success) {
        setSelectedOrder(response.data);
      } else {
        message.error(response.message || '获取订单详情失败');
      }
    } catch (error) {
      console.error('获取订单详情错误:', error);
      message.error('获取订单详情失败');
    } finally {
      setDetailLoading(false);
    }
  };

  useEffect(() => {
    fetchOrders();
  }, []);

  // 表格分页变化
  const handleTableChange = (pagination) => {
    fetchOrders(pagination.current - 1, pagination.pageSize, searchParams);
  };

  // 搜索
  const handleSearch = () => {
    const values = searchForm.getFieldsValue();
    const params = {
      bookName: values.bookName || '',
      startTime: values.dateRange?.[0]?.format('YYYY-MM-DD HH:mm:ss') || null,
      endTime: values.dateRange?.[1]?.format('YYYY-MM-DD HH:mm:ss') || null
    };
    
    setSearchParams(params);
    fetchOrders(0, pagination.pageSize, params);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    setSearchParams({ bookName: '', startTime: null, endTime: null });
    fetchOrders(0, pagination.pageSize);
  };

  // 显示订单详情
  const showOrderDetail = async (order) => {
    setDetailModalVisible(true);
    await fetchOrderDetail(order.id);
  };

  // 关闭订单详情
  const handleDetailCancel = () => {
    setDetailModalVisible(false);
    setSelectedOrder(null);
  };

  // 表格列定义
  const columns = [
    {
      title: '订单编号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 180,
      ellipsis: true
    },
    {
      title: '用户',
      dataIndex: ['user', 'username'],
      key: 'username',
      width: 120,
      ellipsis: true
    },
    {
      title: '订单金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      width: 120,
      render: (amount) => `¥${amount}`
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const statusInfo = ORDER_STATUS[status] || { text: '未知', color: 'default' };
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
      }
    },
    {
      title: '商品数量',
      dataIndex: 'orderItems',
      key: 'itemCount',
      width: 100,
      render: (items) => items?.length || 0
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 160,
      render: (text) => text ? new Date(text).toLocaleString() : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',
      render: (_, record) => (
        <Button
          type="primary"
          size="small"
          icon={<EyeOutlined />}
          onClick={() => showOrderDetail(record)}
        >
          查看
        </Button>
      )
    }
  ];

  return (
    <div>
      <Card>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 16 }}
        >
          <Form.Item name="bookName" label="书籍名称">
            <Input placeholder="请输入书籍名称" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="dateRange" label="时间范围">
            <RangePicker 
              showTime 
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['开始时间', '结束时间']}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button onClick={handleReset} icon={<ReloadOutlined />}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          columns={columns}
          dataSource={orders}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
          }}
          onChange={handleTableChange}
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* 订单详情弹窗 */}
      <Modal
        title="订单详情"
        open={detailModalVisible}
        onCancel={handleDetailCancel}
        footer={[
          <Button key="close" onClick={handleDetailCancel}>
            关闭
          </Button>
        ]}
        width={800}
        loading={detailLoading}
      >
        {selectedOrder && (
          <div>
            <Descriptions title="订单信息" bordered size="small">
              <Descriptions.Item label="订单编号" span={2}>
                {selectedOrder.orderNo}
              </Descriptions.Item>
              <Descriptions.Item label="订单状态">
                <Tag color={ORDER_STATUS[selectedOrder.status]?.color}>
                  {ORDER_STATUS[selectedOrder.status]?.text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="用户名">
                {selectedOrder.user?.username}
              </Descriptions.Item>
              <Descriptions.Item label="用户邮箱">
                {selectedOrder.user?.email}
              </Descriptions.Item>
              <Descriptions.Item label="订单金额">
                ¥{selectedOrder.totalAmount}
              </Descriptions.Item>
              <Descriptions.Item label="创建时间" span={2}>
                {selectedOrder.createTime ? new Date(selectedOrder.createTime).toLocaleString() : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="更新时间">
                {selectedOrder.updateTime ? new Date(selectedOrder.updateTime).toLocaleString() : '-'}
              </Descriptions.Item>
            </Descriptions>

            <Divider />

            <h4>订单商品</h4>
            <Table
              columns={[
                {
                  title: '书籍名称',
                  dataIndex: ['book', 'name'],
                  key: 'bookName'
                },
                {
                  title: '作者',
                  dataIndex: ['book', 'author'],
                  key: 'author'
                },
                {
                  title: '单价',
                  dataIndex: 'price',
                  key: 'price',
                  render: (price) => `¥${price}`
                },
                {
                  title: '数量',
                  dataIndex: 'quantity',
                  key: 'quantity'
                },
                {
                  title: '小计',
                  key: 'subtotal',
                  render: (_, record) => `¥${(record.price * record.quantity).toFixed(2)}`
                }
              ]}
              dataSource={selectedOrder.orderItems || []}
              rowKey="id"
              pagination={false}
              size="small"
            />
          </div>
        )}
      </Modal>
    </div>
  );
};

export default Orders; 